package com.ece.devirtualizus.Dao;

import java.util.ArrayList;
import java.util.List;

import android.util.Log;

import com.parse.ParseException;
import com.parse.ParseInstallation;
import com.parse.ParseObject;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import com.parse.SignUpCallback;

public class FirstConnectionDao implements IFirstConnectionDao {
	String username;
	String headimgId;
	String bodyimgId;
	String legimgId;
	String ParseID = "";

	public FirstConnectionDao() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<String> getAvatar(String userId) {
		// TODO Auto-generated method stub
		List<String> avatarImgId = new ArrayList<String>();

		ParseObject avatar = getAvatarParse(userId);
		avatarImgId.add(avatar.getString("HeadImgId"));
		avatarImgId.add(avatar.getString("BodyImgId"));
		avatarImgId.add(avatar.getString("LegImgId"));

		Log.i("FirstConnectionDao.getAvatar",
				"getAvatar : " + avatarImgId.size());

		if (avatarImgId.size() == 3)
			return avatarImgId;
		else
			return null;
	}

	@Override
	public String createUser(String userName, String deviceId,
			String phoneNumber, String motto, String headImgId,
			String bodyImgId, String legImgId) {
		this.username = userName;
		this.headimgId = headImgId;
		this.bodyimgId = bodyImgId;
		this.legimgId = legImgId;
		// TODO Auto-generated method stub
		final boolean succesStore = false;
		ParseUser user = new ParseUser();
		user.setUsername(userName);
		user.setPassword("");
		// user.setEmail("email@example.com");

		// other fields can be set just like with ParseObject
		user.put("number_phone", phoneNumber);
		user.put("isActive", true);
		user.put("device_Id", deviceId);
		user.put("motto", motto);
		Log.i("FirstConnectionDao.createUser", "Avatar store");
		try {
			user.signUp();
			ConnectionDao connectionDao = new ConnectionDao();
			connectionDao.connection(username, "");
			Log.i("FirstConnectionDao.createUser", "User+ avatar store");
			ParseID = ParseUser.getCurrentUser().getObjectId();
			Log.i("FirstConnectionDao.createUser", "id after creation"
					+ ParseID);
			storeAvatarImgInBdd(ParseID, headimgId, bodyimgId, legimgId);
		} catch (Exception e) {
			// Sign up didn't succeed. Look at the ParseException
			// to figure out what went wrong
			Log.e("FirstConnectionDao.createUser", "User+ avatar not store");
		}

		try {
			ParsePush.subscribeInBackground("N_" + ParseID);
			Log.d("com.parse.push",
					"successfully subscribed to the broadcast channel.");

			Log.i("Parse.initialisaz or connection", "CONNECTE");
			ParseInstallation.getCurrentInstallation().saveInBackground();

		} catch (Exception e) {
			Log.e("com.parse.push", "failed to subscribe for push", e);
			Log.e("FirstConnectionDao.createUser", "User non store store");

		}

		//
		// user.signUpInBackground(
		//
		// //Asynchronous
		// new SignUpCallback() {
		// public void done(ParseException e) {
		// if (e == null) {
		// // Hooray! Let them use the app now.
		// ConnectionDao connectionDao = new ConnectionDao();
		// connectionDao.connection(username, "");
		// Log.i("FirstConnectionDao.createUser",
		// "User+ avatar store");
		// ParseID = ParseUser.getCurrentUser().getObjectId();
		// Log.i("FirstConnectionDao.createUser",
		// "id after creation"+ParseID);
		// storeAvatarImgInBdd(ParseID, headimgId, bodyimgId,
		// legimgId);
		//
		// ParsePush.subscribeInBackground("N_" + ParseID,
		// new SaveCallback() {
		// @Override
		// public void done(ParseException e) {
		// if (e == null) {
		// Log.d("com.parse.push",
		// "successfully subscribed to the broadcast channel.");
		// } else {
		// Log.e("com.parse.push",
		// "failed to subscribe for push",
		// e);
		// }
		// }
		// });
		// Log.i("Parse.initialisaz or connection", "CONNECTE");
		// ParseInstallation.getCurrentInstallation()
		// .saveInBackground();
		// } else {
		// // Sign up didn't succeed. Look at the ParseException
		// // to figure out what went wrong
		// Log.e("FirstConnectionDao.createUser",
		// "User+ avatar not store");
		// }
		// }
		// });
		//
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		//
		// }
		Log.i("FirstConnectionDao.createUser", "id=" + ParseID);
		return ParseID;

		// user.signUpInBackground(new SignUpCallback() {
		// public void done(ParseException e) {
		// if (e == null) {
		// // Hooray! Let them use the app now.
		// succesStore = true;
		// } else {
		// Log.e("FirstConnectionDao.createUser","Erreur lors de la premiere connection ");
		//
		// // Sign up didn't succeed. Look at the ParseException
		// // to figure out what went wrong
		// succesStore= false;
		// }
		// }
		// });

		// return succesStore;
		// }
		// else
		// {
		// Log.e("FirstConnectionDao.createUser","Erreur lors de la premiere connection  retour store avatar mauvais");
		// return succesStore;
		// }

	}

	private ParseObject getAvatarParse(String userId) {
		ParseQuery<ParseObject> query = ParseQuery.getQuery("AvatarImg");
		ParseObject avatarParse = new ParseObject("AvatarImg");
		try {
			avatarParse = query.get(userId);
			Log.i("FirstConnectionDao.getAvatarParse", "getAvatarParse : "
					+ avatarParse.toString());
			return avatarParse;
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return avatarParse;
		}
	}

	private boolean storeAvatarImgInBdd(String IdUser, String headImgId,
			String bodyImgId, String legImgId) {
		ParseObject avatarParse = new ParseObject("AvatarImg");
		// ParseObject typeReleve = new ParseObject("TypeReleve");

		avatarParse.put("idUser", IdUser);
		avatarParse.put("HeadImgId", headImgId);
		avatarParse.put("BodyImgId", bodyImgId);
		avatarParse.put("LegImgId", legImgId);

		try {
			avatarParse.saveInBackground();
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log.e("storeAvatarImgInBdd", "" + e.getMessage());
			return false;
		}
	}

	@Override
	public boolean isAlreadyRegistered(String deviceId) {
		List<ParseObject> listUserRegistered = new ArrayList<ParseObject>();

		ParseQuery<ParseObject> queryTypeReleve = ParseQuery.getQuery("User");
		queryTypeReleve.whereEqualTo("device_Id", deviceId);
		try {
			listUserRegistered = queryTypeReleve.find();
			Log.i("isAlreadyRegistered", "listUserRegistered size : "
					+ listUserRegistered.size());
			if (listUserRegistered.size() == 1) {
				return true;
			} else {
				Log.e("isAlreadyRegistered",
						"User non registered, listUserRegistered size : "
								+ listUserRegistered.size());
				return false;
			}
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			Log.e("isAlreadyRegistered", "Erreur lors de la requete");
			return false;
		}
	}

	@Override
	public String getUserNameByDeviceId(String deviceId) {
		// TODO Auto-generated method stub
		String userName = "";
		ParseUser userParse = new ParseUser();

		ParseQuery<ParseUser> query = ParseUser.getQuery();
		query.whereEqualTo("device_Id", deviceId);

		try {
			userParse = query.getFirst();
			userName = userParse.getString("username");
			Log.i("getUserNameByDeviceId", "Username = " + userName);
			return userName;
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			Log.e("isAlreadyRegistered", "Erreur lors de la requete");
			return userName;
		}
	}

	@Override
	public boolean isUserNameInBdd(String userName) {
		// TODO Auto-generated method stub

		// TODO Auto-generated method stub
		List<ParseUser> listParseUser = new ArrayList<ParseUser>();

		ParseQuery<ParseUser> query = ParseUser.getQuery();
		query.whereEqualTo("username", userName);
		try {
			listParseUser = query.find();
			Log.i("isUserNameInBdd",
					"listParseUser size : " + listParseUser.size());
			if (listParseUser.size() > 0) {
				return true;
			} else {
				Log.i("isUserNameInBdd", "UserName not in bdd");
				return false;
			}
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			Log.e("isUserNameInBdd", "Erreur lors de la requete");
			return false;
		}
	}

	@Override
	public String getHeadImgIdByUser(String userId) {
		// TODO Auto-generated method stub
		String headImgId = "";

		ParseObject avatarImg = new ParseObject("AvatarImg");

		ParseQuery<ParseObject> query = ParseQuery.getQuery("AvatarImg");
		query.whereEqualTo("idUser", userId);
		try {
			avatarImg = query.getFirst();
			Log.i("getHeadImgIdByUser",
					"avatarImg : " + avatarImg.getString("HeadImgId"));
			headImgId = avatarImg.getString("HeadImgId");
			return headImgId;
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			Log.e("getHeadImgIdByUser", "Erreur lors de la requete");
			return headImgId;
		}
	}

	@Override
	public String getBodyImgIdByUser(String userId) {
		// TODO Auto-generated method stub
		String bodyImgId = "";

		ParseObject avatarImg = new ParseObject("AvatarImg");

		ParseQuery<ParseObject> query = ParseQuery.getQuery("AvatarImg");
		query.whereEqualTo("idUser", userId);
		try {
			avatarImg = query.getFirst();
			Log.i("getBodyImgIdByUser",
					"avatarImg : " + avatarImg.getString("BodyImgId"));
			bodyImgId = avatarImg.getString("BodyImgId");
			return bodyImgId;
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			Log.e("getBodyImgIdByUser", "Erreur lors de la requete");
			return bodyImgId;
		}
	}

	@Override
	public String getLegImgIdByUser(String userId) {
		// TODO Auto-generated method stub
		String legImgId = "";
		ParseObject avatarImg = new ParseObject("AvatarImg");

		ParseQuery<ParseObject> query = ParseQuery.getQuery("AvatarImg");
		query.whereEqualTo("idUser", userId);
		try {
			avatarImg = query.getFirst();
			Log.i("getLegImgIdByUser",
					"avatarImg : " + avatarImg.getString("LegImgId"));
			legImgId = avatarImg.getString("LegImgId");
			return legImgId;
		} catch (ParseException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			Log.e("getLegImgIdByUser", "Erreur lors de la requete");
			return legImgId;
		}
	}

}
